from django import forms
from django.shortcuts import render
from django.apps import apps
from .models import *
from .forms import StopForm
import os


class LineStop(object):
    def __init__(self, line, direction, stop):
        self.to_line = line
        self.to_direction = direction
        self.to_stop = stop


city_list = {
    '大连': 'dalian',
    '广州': 'guangzhou',
    '杭州': 'hangzhou',
    '昆明': 'kunming',
    '南京': 'nanjing',
    '上海': 'shanghai',
    '天津': 'tianjin',
}
fifo_send = r"\\.\pipe\fifo_r"
fifo_recv = r"\\.\pipe\fifo_w"
pipe_buffer_size = 65536


def index(request):
    return render(request, 'advisor/index.html',
                  context={'city_list': city_list,
                           'index': True})


def select_city(request, city):
    return render(request, 'advisor/index.html',
                  context={'city_list': city_list,
                           'city': city})


def show_stops(request, city, stop_prefix):
    pass


def query(request, city):
    if request.method == 'GET':
        return render(request, 'advisor/index.html',
                      context={
                          'city_list': city_list,
                          'city': city,
                          'new_form': 1
                      })
    else:
        lines_table_name = city[0].upper() + city[1:]
        stops_table_name = lines_table_name + 'Stops'
        lines_table = globals()[lines_table_name]
        stops_table = globals()[stops_table_name]
        form = StopForm()
        form.start = request.POST['start']
        form.end = request.POST['end']
        start = stops_table.objects.filter(stop_name__exact=form.start)
        end = stops_table.objects.filter(stop_name__exact=form.end)

        if not (start.count() and end.count()):
            # messages.add_message(request, messages.ERROR, '评论发表失败! 请修改后重新提交。', extra_tags='danger')
            start_error = ""
            end_error = ""
            if not start.count():
                start_error = '未查找到该站点'
            if not end.count():
                end_error = '未查找到该站点'
            context = {
                'city_list': city_list,
                'city': city,
                'form': form,
                'new_form': 0,
                'start_error': start_error,
                'end_error': end_error,
            }
            return render(request, 'advisor/index.html', context=context)

        start = start[0]
        end = end[0]

        if start.stop_id == end.stop_id:
            end_error = '起点与终点不能重复'
            context = {
                'city_list': city_list,
                'city': city,
                'form': form,
                'new_form': 0,
                'end_error': end_error,
            }
            # messages.add_message(request, messages.ERROR, '评论发表失败! 请修改后重新提交。', extra_tags='danger')
            return render(request, 'advisor/index.html', context=context)

        msg = city + ' ' + str(start.stop_id) + ' ' + str(end.stop_id)
        data = os.popen('solver.exe ' + msg).readlines()

        succ = int(data[0])
        lines = {
            'line_1_cost': succ,
            'line_2_cost': 0,
        }
        if 0 == succ:
            return render(request, 'advisor/index.html',
                          context={'city_list': city_list,
                                   'result': True})
        else:

            lines_1 = data[1].split()[1:]
            lines['stops_1'] = [LineStop(None, None, start.stop_name)]
            lines['stops_1'].extend([LineStop(lines_table.objects.get(line_id=int(lines_1[i]) // 2).line_name,
                                              '下行' if int(lines_1[i]) % 2 else '上行',
                                              stops_table.objects.get(stop_id=lines_1[i + 1]).stop_name)
                                     for i in range(0, len(lines_1), 2)])

            lines['line_2_cost'] = int(data[2])

            lines_2 = data[3].split()[1:]
            lines['stops_2'] = [LineStop(None, None, start.stop_name)]
            lines['stops_2'].extend([LineStop(lines_table.objects.get(line_id=int(lines_2[i]) // 2).line_name,
                                              '下行' if int(lines_2[i]) % 2 else '上行',
                                              stops_table.objects.get(stop_id=lines_2[i + 1]).stop_name)
                                     for i in range(0, len(lines_2), 2)])
            lines['time'] = ("%.4f" % float(data[4]))

            context = {'city_list': city_list,
                       'result': True,
                       'success': True}
            context.update(lines)
            return render(request, 'advisor/index.html', context=context)

